#include <iostream>
#include "TcpServer.hpp"
#include <stdio.h>

// ./client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "PLEASE USAGE ./CLIENT IP PORT" << std::endl;
    }
    std::string sport = argv[2];
    int port = stoi(sport);

    std::string sip = argv[1];

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);

    // 客户端的信息
    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    memset(&server, 0, sizeof(server));

    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(sip.c_str());
    int n = connect(sockfd, CONV(&server), len);
    if (n != 0)
    {
        LOG(LogLevel::FATAL) << "connect server failed";
        Die(CONNECT_ERR);
    }
    
    LOG(LogLevel::INFO) << "connect success, sockfd is : " << sockfd;



    while (true)
    {
        std::cout << "input message# ";
        std::string message;
        std::getline(std::cin, message);

        int n = send(sockfd, message.c_str(), sizeof(message), 0);
        if (n > 0)
        {
            char buffer[4096];
            int n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            buffer[n] = 0;
            LOG(LogLevel::INFO) << buffer;
        }
    }
}